<?php

namespace App\Http\Middleware;

use App\Models\OsanGroupUser;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $uid = $request->jwt['uid'];
        // 获取用户的是否有管理员角色,存在往下走，不存在报错
        // 不存在
        if (!OsanGroupUser::query()->where('uid', $uid)->where('gid', 1)->exists()) {
            return $this->NotAdminError();
        }
        return $next($request);
    }

    protected function NotAdminError(): JsonResponse
    {
        return response()->json([
            "code" => -1,
            "msg" => "No administrator privileges",
            "data" => [],
        ]);
    }
}
